package com.spx.core.wizards;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.IWizardPage;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.INewWizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchWizard;

import com.spx.core.services.security.AuthorizationUtil;
import com.spx.kernel.types.ModelType;

/**
 * This is a sample new wizard. Its role is to create a new file resource in the
 * provided container. If the container resource (a folder or a project) is
 * selected in the workspace when the wizard is opened, it will accept it as the
 * target container. The wizard creates one file with the extension "mpe". If a
 * sample multi-basic editor (also available as a template) is registered for
 * the same extension, it will be able to open it.
 */

public abstract class NewModelObjectWizard<T extends ModelType> extends Wizard implements INewWizard
{

	private T modelObject;

	protected List<ModelWizardPage<T>> pages = new ArrayList<ModelWizardPage<T>>();

	/**
	 * Constructor for NewUserWizard.
	 */
	public NewModelObjectWizard()
	{
		super();

	}

	/**
	 * Adding the basic to the wizard.
	 */

	@Override
	final public void addPages()
	{
		if (AuthorizationUtil.isAuthorized(getClass()))
		{
			for (final IWizardPage page : pages)
			{
				addPage(page);
			}
		}
	}

	/**
	 * This method is called when 'Finish' button is pressed in the wizard. We
	 * will create an operation and run it using wizard as execution context.
	 */
	@Override
	public boolean performFinish()
	{
		buildProperties();
		finish();

		return true;
	}

	public void buildProperties()
	{

		if (AuthorizationUtil.isAuthorized(getClass()))
		{
			for (final ModelWizardPage<T> page : pages)
			{
				page.setProperties(modelObject);
			}
		}

	}

	public abstract void finish();

	/**
	 * We will accept the selection in the workbench to see if we can initialize
	 * from it.
	 * 
	 * @see IWorkbenchWizard#init(IWorkbench, IStructuredSelection)
	 */
	public void init(IWorkbench workbench, IStructuredSelection selection)
	{

	}

	public void setModelObject(T object)
	{
		this.modelObject = object;
	}

	public T getModelObject()
	{
		if (modelObject != null)
		{
			for (final ModelWizardPage<T> page : pages)
			{
				page.setProperties(modelObject);
			}
		}
		return this.modelObject;
	}
}